package chef.myapplication.model;

import chef.myapplication.Main;
import chef.myapplication.controller.MainController;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.effect.ColorAdjust;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.layout.GridPane;
import javafx.stage.Modality;
import javafx.stage.Stage;


import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

public class ImageBoxes {
     private static final Button cancelButton=new Button("取消");//用于重命名
     public static ContextMenu contextMenu = new ContextMenu();
     private   static Stage FunctionUIStage;
     private  static File currentImageFile;
     private static final ArrayList<ImageBox> imageBoxes=new ArrayList<>();
     private static final ArrayList<ImageBox> selectedImageBoxes = new ArrayList<>();
     private static final ArrayList<File> copiedFiles =new ArrayList<>();
     //重命名-----
     //   private static boolean single;
     private static Stage RenameStage;
     private static Label message;
     private static Button button;
     private static GridPane grid;//重命名的窗口
     final private static TextField name = new TextField();
     final private static TextField startNum = new TextField();
     final private static TextField bitNum = new TextField();
     //-------
     private static	String fubenString="-副本";
     private static int fubenCount =0;
     private static String nameString;

     public static  void  checkAll(){
          for (ImageBox imageBox : imageBoxes) {
               imageBox.getCheckBox().setSelected(true);
          }
     }
     public static void uncheck(){
          for (ImageBox imageBox : imageBoxes) {
               imageBox.getCheckBox().setSelected(false);
          }
     }

     public static void deleteSelectedImageBoxes(){
          for (ImageBox imageBox : imageBoxes) {
               if (imageBox.getCheckBox().isSelected()) {
                    imageBox.delete();
               }
          }
          MainController.getMainController().Refresh();
     }
     public static void copySelectedImageBoxes(){

          Clipboard clipboard = Clipboard.getSystemClipboard();
          ClipboardContent clipboardContent = new ClipboardContent();
          clipboard.clear();

          for (ImageBox selectedImageBox : selectedImageBoxes) {
               copiedFiles.add(selectedImageBox.getFile());
          }
          clipboardContent.putFiles(copiedFiles);
          clipboard.setContent(clipboardContent);
     }
     public static void cutImageBoxes() {
          copiedFiles.clear();
          for (ImageBox selectedImageBox : selectedImageBoxes)
               selectedImageBox.setEffect(new ColorAdjust(0, 0, 0.5, 0));
          copySelectedImageBoxes();
          uncheck();
     }
     public static void renameImageBoxes(boolean single) {
          RenameStage = new Stage();
          grid = new GridPane();
          message = new Label();
          button = new Button("完成");

          setStage(single);
     }

     public static void clear()
     {
          imageBoxes.clear();
          selectedImageBoxes.clear();
     }
     public static void paste() throws IOException{
          clearCutImageBoxes();
          int j;
          Clipboard clipboard = Clipboard.getSystemClipboard();
          List<File> pasteFiles=clipboard.getFiles();

          for(int i=0;i<pasteFiles.size();i++)
          {
               int flag1=0;
               for(j=0;j<imageBoxes.size();j++)
               {
                    if(pasteFiles.get(i).getName().equals(imageBoxes.get(j).getFile().getName()))
                    {
                         flag1=1;
                         break;
                    }
               }

               if (flag1==1) {
                    if(MyAlert.showAlert2("是否覆盖当前目录下的"+pasteFiles.get(i).getName(), "", Main.getMainStage()))
                    {

                         if(!imageBoxes.get(j).getFile().equals(pasteFiles.get(i))) {
                              if(imageBoxes.get(j).getFile().delete()){
                                   System.out.println("删除成功");
                              }
                              Path sourcePath = pasteFiles.get(i).toPath();
                              Path newDir = FileTree.getCurrentFile().toPath();
                              try {
                                   Files.copy(sourcePath, newDir.resolve(sourcePath.getFileName()));
                              }
                              catch (IOException e) {
                                   e.printStackTrace();
                              }
                         }
                    }
                    else {
                         fubenCount =0;
                         fubenString="-副本";
                         nameString=pasteFiles.get(i).getName();
                         sameNameRename(i);
                    }
               }
               else {
                    Path sourcePath = pasteFiles.get(i).toPath();
                    Path newDir = FileTree.getCurrentFile().toPath();
                    try {
                         Files.copy(sourcePath, newDir.resolve(sourcePath.getFileName()));
                    }
                    catch (IOException e) {
                         e.printStackTrace();
                    }
               }
               MainController.getMainController().Refresh();
          }

          for (File file : pasteFiles)
               MainController.getMainController().getFlowPane().getChildren().add(new ImageBox(file));
          MainController.getMainController().Refresh();
          if(MainController.getMainController().getFlag_Cut())
               for (File pasteFile : pasteFiles)
                    System.out.println("delete:"+pasteFile.delete());
     }
     private static void setStage(boolean single) {
          RenameStage.setResizable(false);
          RenameStage.initOwner(Main.getMainStage());
          RenameStage.alwaysOnTopProperty();
          RenameStage.initModality(Modality.WINDOW_MODAL);
          grid.setPadding(new Insets(10, 10, 10, 10));
          grid.setVgap(5);
          grid.setHgap(5);
          Label label1 = new Label("名称");
          GridPane.setConstraints(label1, 0, 0);
          name.setText(null);
          name.setPromptText("请输入新名字");
          name.setPrefColumnCount(20);
          name.getText();
          GridPane.setConstraints(name, 1, 0);
          grid.getChildren().addAll(label1,name);
          if(single) {
               GridPane.setConstraints(message, 0, 1);
               GridPane.setConstraints(button, 0, 2);
               GridPane.setConstraints(cancelButton,3,2);
               grid.getChildren().addAll(cancelButton,button,message);
          }else {
               Label label2 = new Label("起始编号");
               GridPane.setConstraints(label2, 0, 1);
               startNum.setText(null);
               startNum.setPromptText("请输入起始编号");
               startNum.setPrefColumnCount(15);//用于计算TextField的首选宽度
               startNum.getText();
               GridPane.setConstraints(startNum, 1, 1);
               Label label3 = new Label("编号位数");
               GridPane.setConstraints(label3, 0, 2);
               bitNum.setText(null);
               bitNum.setPromptText("请输入编号位数");
               bitNum.setPrefColumnCount(10);
               bitNum.getText();
               GridPane.setConstraints(bitNum, 1, 2);
               GridPane.setConstraints(message, 1, 3);
               GridPane.setConstraints(button, 0, 4);
               GridPane.setConstraints(cancelButton,4,4);
               grid.getChildren().addAll(label2,startNum,label3,bitNum,button,cancelButton,message);
          }
          button.setOnAction(e -> {
               if(single) if ((name.getText() != null && !name.getText().isEmpty())) {
                    if (renameSingle()) {
                         RenameStage.close();
                    } else {
                         message.setText("已有该名字的图片存在，请重新输入");//可以输入自己的名字
                    }
               } else {
                    message.setText("你没有输入，请输入!");
               }
               else {
                    if ((name.getText() != null && !name.getText().isEmpty())
                            &&(startNum.getText() != null && !startNum.getText().isEmpty())
                            &&(bitNum.getText() != null && !bitNum.getText().isEmpty())) {
                         if(renameMore()) {
                              RenameStage.close();
                         }else {
                              message.setText("输入错误，请输入其他内容");
                         }
                    } else {
                         message.setText("你没有输入完整的信息，请继续输入.");
                    }
               }
          });
          cancelButton.setOnAction(e-> RenameStage.close());
          Scene scene=new Scene(grid);
          RenameStage.setTitle("重命名");
          RenameStage.setScene(scene);
          RenameStage.show();
          if (!RenameStage.isShowing()) {
               uncheck();
          }

     }
     private static boolean renameSingle() {
          ImageBox imageBox = selectedImageBoxes.get(0);
          File file = imageBox.getFile();
          String pre = file.getParent();
          String[] strings = file.getName().split("\\.");
          String suf = strings[strings.length-1];
          File tmp = new File(pre+"\\"+name.getText()+"."+suf);

          if(!file.renameTo(tmp)) {
               return false;
          }
          MainController.getMainController().Refresh();
          return true;
     }
     private static boolean renameMore() {
          File file;
          int id = Integer.parseInt(startNum.getText());
          int bit = Integer.parseInt(bitNum.getText());
          if( id<0 || (id + selectedImageBoxes.size()) >= (int)Math.pow(10, bit))
               return false;
          for (ImageBox image : selectedImageBoxes) {
               file = image.getFile();
               String pre = file.getParent();
               String[] strings = file.getName().split("\\.");
               String suf = strings[strings.length-1];
               String newName = createName(id,bit);
               File tmp = new File(pre+"\\"+newName+"."+suf);
               if(!file.renameTo(tmp))//可能存在失败的情况,如名字重复
                    return false;
               id++;
          }

          if (!RenameStage.isShowing()) {
               uncheck();
          }
          MainController.getMainController().Refresh();
          return true;
     }
     private static String createName(int id,int bit) {
          StringBuilder newName = new StringBuilder(name.getText());
          int tt = id;
          int cnt=0;
          while(tt!=0) {
               cnt++;
               tt/=10;
          }
          if(id==0)  cnt++;
          while(bit>cnt) {
               newName.append(0);
               cnt++;
          }
          newName.append(id);
          return newName.toString();
     }
     public static void clearCutImageBoxes() {
          for (ImageBox imageBox : imageBoxes) imageBox.setEffect(null);
     }

     public static void sameNameRename(int i)
     {
          String str=imageBoxes.get(i).getFile().getParent();
          try {
               FileInputStream fileInputStream = new FileInputStream(copiedFiles.get(i));
               File newFile=new File(str+"\\"+nameString.substring(0,nameString.lastIndexOf("."))+fubenString+".jpg");
               if (newFile.exists()) {
                    fubenCount++;
                    fubenString="-副本"+ fubenCount;
                    sameNameRename(i);
               }
               try {
                    FileOutputStream fileOutputStream = new FileOutputStream (newFile);
                    int len;
                    byte[] buffer= new byte[1024];
                    while ((len=fileInputStream.read(buffer))!=-1) {
                         fileOutputStream.write(buffer, 0, len);
                         fileOutputStream.flush();
                    }
                    fileInputStream.close();
                    fileOutputStream.close();
               } catch (FileNotFoundException e) {
                    e.printStackTrace();
               } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
               }
          } catch (FileNotFoundException e) {
               e.printStackTrace();
          }
     }

     public static void setFunctionUIStage(Stage functionUIStage) {
          FunctionUIStage = functionUIStage;
     }

     public static void setCurrentImageFile(File file){
          currentImageFile=file;
     }

     public static File getCurrentImageFile() {
          return currentImageFile;
     }
     public static ArrayList<File> getCopiedFile(){
          return copiedFiles;
     }

     public static Stage getFunctionUIStage() {
          return FunctionUIStage;
     }
     public static ArrayList<ImageBox> getImageBoxes(){
          return imageBoxes;
     }
     public static  ArrayList<ImageBox> getSelectedImageBoxes(){
          return selectedImageBoxes;
     }

}
